package com.yss.common.core.utils.easyexecl;

import com.yss.common.core.annotation.ExcelValid;
import com.yss.common.core.enums.YssRegularEnum;
import com.yss.common.core.exception.BusinessException;
import com.yss.common.core.utils.StringUtils;

import java.lang.reflect.Field;
import java.util.Objects;
import java.util.regex.Pattern;


public class ExcelImportValid {
    /**
     * Excel导入字段校验
     *
     * @param object 校验的JavaBean 其属性须有自定义注解
     */
    public static void valid(Object object) throws Exception {
        Field[] fields = object.getClass().getDeclaredFields();
        for (Field field : fields) {
            //设置可访问
            field.setAccessible(true);
            //属性的值
            Object fieldValue = null;
            try {
                fieldValue = field.get(object);
            } catch (IllegalAccessException e) {
                throw new BusinessException("导入参数检查失败");
            }
            //是否包含必填校验注解
            boolean isExcelValid = field.isAnnotationPresent(ExcelValid.class);
            if (!isExcelValid) {
                continue;
            }
            if (Objects.isNull(fieldValue)) {
                throw new BusinessException(field.getAnnotation(ExcelValid.class).message());
            }
            // 配置了正则表达式
            String regexp = field.getAnnotation(ExcelValid.class).regexp();
            if (StringUtils.isEmpty(regexp)) {
                continue;
            }
            if (!Pattern.matches(regexp, String.valueOf(fieldValue))) {
                throw new BusinessException(field.getAnnotation(ExcelValid.class).message());
            }
        }
    }
}
